package com.crv.ci.agent.queue.producer;

import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;

import javax.jms.*;

/**
 * Created by lip on 2015-12-17.
 */
public class SendTasker {

    private static SendTasker instance = null;
    private ActiveMQConnectionFactory connectionFactory;
    private String user = ActiveMQConnection.DEFAULT_USER;
    private String password = ActiveMQConnection.DEFAULT_PASSWORD;
    private String url = "tcp://127.0.0.1:61616";
//    private String subject = "GagosQueues/Command";
//    private Destination destination = null;
    private Connection connection = null;
    private Session session = null;
    private MessageProducer producer = null;

    private SendTasker() throws Exception {
        initialize();
    };

    public static SendTasker getInstance() throws Exception {
        instance = new SendTasker();
        return instance;
    }

    // 初始化
    private void initialize() throws JMSException, Exception {
        // 连接工厂是用户创建连接的对象，这里使用的是ActiveMQ的ActiveMQConnectionFactory根据url，username和password创建连接工厂。
        connectionFactory = new ActiveMQConnectionFactory(
                user, password, url);
        // 连接工厂创建一个jms connection
        connection = connectionFactory.createConnection();
        // 是生产和消费的一个单线程上下文。会话用于创建消息的生产者，消费者和消息。会话提供了一个事务性的上下文。
        session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); // 不支持事务


    }

    // 关闭连接
    public void close() throws JMSException {
        if (producer != null)
            producer.close();
        if (session != null)
            session.close();
        if (connection != null)
            connection.close();
    }



    public static void sendMessage(String msg,String subject)
            throws Exception {
        SendTasker sendTasker = getInstance();
        Session session = sendTasker.session;
        MessageProducer producer = sendTasker.producer;

        sendMessage(session,producer,msg,subject);
    }

    private static  void sendMessage(Session session, MessageProducer producer,String msg,String subject)
            throws Exception {

        // 目的地是客户用来指定他生产消息的目标还有他消费消息的来源的对象，两种消息传递方式：点对点和发布/订阅
        Destination  destination = session.createQueue(subject);
        // 会话创建消息的生产者将消息发送到目的地
//        consumer = session.createConsumer(destination);
        producer = session.createProducer(destination);
        // 设置不持久化，此处学习，实际根据项目决定
        producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);

            TextMessage message = session
                    .createTextMessage(msg);

            // 发送消息到目的地方
            System.out.println(msg);
            producer.send(message);
    }
}
